import os
from PIL import Image, ImageFilter

from paddleocr import PaddleOCR, draw_ocr

# from paddleOrc import PaddleOCR, draw_ocr
# 模型路径下必须含有model和params文件
config = {
    'baseFile': "C:\\Users\\DingMiaoBin\\Desktop\\资料\\数字图像处理技术"
}


def test():
    ocr = PaddleOCR(use_angle_cls=True,
                    use_gpu=False)  # det_model_dir='{your_det_model_dir}', rec_model_dir='{your_rec_model_dir}', rec_char_dict_path='{your_rec_char_dict_path}', cls_model_dir='{your_cls_model_dir}', use_angle_cls=True
    img_path = 'C:\\Users\\DingMiaoBin\\Desktop\\资料\\数字图像处理技术\\1629277289.png'
    result = ocr.ocr(img_path, cls=True)
    for line in result:
        print(line)
    # 显示结果
    from PIL import Image
    image = Image.open(img_path).convert('RGB')
    boxes = [line[0] for line in result]
    txts = [line[1][0] for line in result]
    scores = [line[1][1] for line in result]
    im_show = draw_ocr(image, boxes, txts, scores, font_path='C:\\Windows\\Fonts\\simfang.ttf')
    im_show = Image.fromarray(im_show)
    im_show.save('result1111.jpg')  # 结果图片保存在代码同级文件夹中。


ocr = PaddleOCR(use_angle_cls=True,
                use_gpu=False)  # det_model_dir='{your_det_model_dir}', rec_model_dir='{your_rec_model_dir}', rec_char_dict_path='{your_rec_char_dict_path}', cls_model_dir='{your_cls_model_dir}', use_angle_cls=True


def outPutMarkDown(line, imageFile):
    return '```\n' \
    + line + \
    '```\n'\
    +'![](' + fileName + ')'



def analyzePicture(img_path):
    global ocr
    result = ocr.ocr(img_path, cls=True)
    lines = ""
    for line in result:
        # print(line[1])
        lines = lines + str(line[1][0]) + "\n"
    return lines


if __name__ == '__main__':
    fileList = []
    for root, dirs, files in os.walk(config['baseFile']):
        for file in files:
            if os.path.splitext(file)[1] == '.png':
                fileList.append(os.path.join(root, file))
    markDownStr = []
    for fileName in fileList:
        myImage = Image.open(fileName)
        x = analyzePicture(fileName)
        markDownStr.append(outPutMarkDown(x, fileName))
    # 写入markdown文件

    for markDown1 in markDownStr:
        print(markDown1)
